<script setup lang="ts">
import { SearchForm, SearchTable } from '@fl/components'
import type { DataIndex } from '@fl/api/anjutong/model/qualification-ticket-model'
import { cloneDeep } from 'lodash-es'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import type { PlusColumn } from 'plus-pro-components'
import { useDataExport, useDataIndex, useDataStatistic } from '@fl/api/anjutong/qualification-ticket'
import { formatTime } from '@fl/utils'

const visible = defineModel<boolean>('visible', { required: true })
const scanId = defineModel<string>('id', { required: true })
const tagList = ref<any>([])
const tableHeight = ref<number>(200)

// 搜索条件、分页参数
const initialState = {
    date: ['', ''],
    startTime: '',
    endTime: '',
}
const state = ref<DataIndex>(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))

// 查询列表
const params = computed(() => ({
    pageIndex: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    qualificationId: scanId.value,
    endTime: formatTime(state.value.date?.[1], 'yyyy-MM-dd 23:59:59'),
    startTime: formatTime(state.value.date?.[0], 'yyyy-MM-dd 00:00:00'),
}))

const records = ref<any>()
const formRef = ref()
const { data, isLoading } = useDataIndex(params)
// 数据统计
const dataParams = computed(() => ({
    qualificationId: scanId.value,
    endTime: formatTime(state.value.date?.[1], 'yyyy-MM-dd 23:59:59'),
    startTime: formatTime(state.value.date?.[0], 'yyyy-MM-dd 00:00:00'),
}))
const { data: detail } = useDataStatistic(dataParams)

watchEffect(() => {
    if (data.value) {
        records.value = cloneDeep(data.value.records)
        tablePage.value.total = data.value.total!
    }
    if (detail.value) {
        tagList.value = [
            {
                field: 'scanNum',
                num: detail.value.scanNum || 0,
                title: '扫码张数',
            },
            {
                field: 'scanPeopleNum',
                num: detail.value.scanPeopleNum || 0,
                title: '扫码人数',
            },
            {
                field: 'receiveNum',
                num: detail.value.receiveNum || 0,
                title: '领取人数',
            },
            {
                field: 'receiveSuccessNum',
                num: detail.value.receiveSuccessNum || 0,
                title: '领取成功人数',
            },
        ]
    }
})

function cancel() {
    visible.value = false
    scanId.value = ''
    reset()
}

// 搜索
function submit(values: DataIndex) {
    state.value = { ...values }
    tablePage.value.currentPage = 1
}

// 重置
function reset() {
    formRef.value?.formInstance.formInstance.resetFields()
    state.value.date = []
    tablePage.value = initialPage
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

// 导出
const exportParams = computed(() => ({
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
    qualificationId: scanId.value,
    endTime: formatTime(state.value.date?.[1], 'yyyy-MM-dd 23:59:59'),
    startTime: formatTime(state.value.date?.[0], 'yyyy-MM-dd 00:00:00'),
}))
const { isPending, mutateAsync } = useDataExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        // const objectUrl = URL.createObjectURL(res)
        // location.href = objectUrl
        // URL.revokeObjectURL(objectUrl)
        const content = res
        const blob = new Blob([content])
        const d = new Date()
        const filename = `领取数据_${d.getFullYear()}-${
            d.getMonth() + 1
        }-${d.getDate()}.xlsx`
        if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = filename
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
        }
    }
}

const columns: PlusColumn[] = [
    {
        colProps: { span: 12 },
        fieldProps: {
            'endPlaceholder': '结束时间',
            'startPlaceholder': '开始时间',
            'type': 'daterange',
            'value-format': 'YYYY-MM-DD',
        },
        label: '领取时间',
        prop: 'date',
        valueType: 'date-picker',
    },
]

const gridOptions = reactive({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'userName', title: '用户名称' },
        // { field: 'projectName', title: '项目名称' },
        { field: 'userPhone', title: '联系方式' },
        { field: 'authType', title: '认证类型' },
        { field: 'userIdCard', title: '用户证件号' },
        { field: 'createTime', title: '领取时间' },
    ],
})
</script>

<template>
    <PlusDialog v-model="visible"
                title="数据"
                :has-footer="false"
                width="1040"
                @cancel="cancel"
                @closed="reset"
    >
        <div class="coupon-info">
            <div class="base-info">
                <dl v-for="tag in tagList"
                    :key="tag.title"
                    :class="['scanNum', 'scanPeopleNum'].includes(tag.field) ? 'tag sheet-num' : 'tag people-num'"
                >
                    <dt>{{ tag.title }}</dt>

                    <dd>{{ tag.num }}</dd>
                </dl>
            </div>
        </div>

        <SearchForm ref="formRef"
                    v-bind="state"
                    :columns="columns"
                    submit-text="搜索"
                    @reset="reset"
                    @submit="submit"
        />

        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isLoading"
                     :data="records"
                     :height="tableHeight"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <!-- style="margin-top:-50px;" -->
                <ElButton type="primary"
                          plain
                          :loading="isPending"

                          @click="exportData"
                >
                    <div class="i-iconamoon:upload size-16" />
                    导出
                </ElButton>
            </template>
        </SearchTable>
    </PlusDialog>
</template>

<style lang="scss" scoped>
.coupon-info {
    margin-bottom: 20px;
    :deep(.vxe-table--body-wrapper .body--wrapper) {
        height: 100px !important;
        min-height: 100px !important;
    }
    .base-info {
        display: flex;
        .tag {
            flex: 1;
            height: 70px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin: 0;
            margin-right: 20px;
            padding: 0;
            dt {
                font-size: 16px;
                margin: 0;
                padding: 0;
            }
            dd {
                font-size: 24px;
                font-weight: 600;
                margin: 0;
                padding: 0;
            }
            &.sheet-num {
                background-color: #e5f0fa;
                dd {
                    color: #006dcc;
                }
            }
            &.people-num {
                background-color: #fff0f0;
                dd {
                    color: #da0004;
                }
            }
        }
    }
}

:deep(.plus-form__footer) {
    // margin-top: -50px;
    position: absolute;
    right: 32px;
    top: 164px;
    z-index: 999;
}
</style>
